package gold.digger;

import gold.utils.InputUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1262 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int maxSumDivThree(int[] nums) {
            List<Integer> oneList = new ArrayList<>(), twoList = new ArrayList<>();

            int sum = 0;
            for (int num : nums) {
                sum += num;
                if (num % 3 == 2) twoList.add(num);
                else if (num % 3 == 1) oneList.add(num);
            }

            if (sum % 3 == 0) return sum;
            oneList.sort(Comparator.naturalOrder());
            twoList.sort(Comparator.naturalOrder());
            if (sum % 3 == 1) {
                // 1可以由2+2 = 4 % 3 == 1 得到
                if (twoList.size() >= 2 && twoList.get(0) + twoList.get(1) < oneList.get(0))
                    return sum - twoList.get(0) - twoList.get(1);
                else return sum - oneList.get(0);

            } else {
                if (oneList.size() >= 2 && oneList.get(0) + oneList.get(1) < twoList.get(0))
                    return sum - oneList.get(0) - oneList.get(1);
                else return sum - twoList.get(0);
            }
        }
    }

    public void run() {
        System.out.println(new Solution().maxSumDivThree(InputUtil.toIntegerArray("[3,6,5,1,8]")));
        System.out.println(new Solution().maxSumDivThree(InputUtil.toIntegerArray("[4]")));
        System.out.println(new Solution().maxSumDivThree(InputUtil.toIntegerArray("[1,2,3,4,4]")));
        System.out.println(new Solution().maxSumDivThree(InputUtil.toIntegerArray("[2,6,2,2,7]")));
    }

    public static void main(String[] args) throws Exception {
        LC1262 an = new LC1262();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
